Check Prime Number Using User-defined Function using C++

04-11-17 Course- CPP

In this program, user is asked to enter a positive integer and this program checks whether that number is a Prime number or not. To perform this task, a user-defined functions is defined.


/* C++ program to check Prime number. */
#include <iostream>
using namespace std;
int check_prime(int n);
int main()
{
  int n, temp=0;
  cout << "Enter a positive  integer: ";
  cin >> n;
  temp=check_prime(n);
  
  if(temp==0)
    cout << n << " is a prime number.";
  else
    cout << n << " is not a prime number.";
  return 0;
}
int check_prime(int n)
{
  int i, flag=0;
  for(i=2;i<=n/2;++i)
  {
      if(n%i==0)
      {
          flag=1;
          break;
      }
  }
  return flag;
}

Output


Enter a positive integer: 371
371 is an Armstrong number.